package com.rla.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.rla.common.core.page.TableDataInfo;
import com.rla.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.rla.common.utils.SecurityUtils;
import com.rla.common.utils.StringUtils;
import com.rla.domain.PointsDetails;
import com.rla.domain.VipUserInfo;
import com.rla.mapper.PointsDetailsMapper;
import com.rla.mapper.VipUserInfoMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import com.rla.domain.bo.IntegralTaskBo;
import com.rla.domain.vo.IntegralTaskVo;
import com.rla.domain.IntegralTask;
import com.rla.mapper.IntegralTaskMapper;
import com.rla.service.IIntegralTaskService;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Collection;

import static com.rla.common.utils.SecurityUtils.getUsername;

/**
 * 积分任务Service业务层处理
 *
 * @author rla
 * @date 2025-09-11
 */
@RequiredArgsConstructor
@Service
public class IntegralTaskServiceImpl implements IIntegralTaskService {

    private final IntegralTaskMapper baseMapper;

    private final PointsDetailsMapper pointsDetailsMapper;

    private final VipUserInfoMapper vipUserInfoMapper;

    /**
     * 查询积分任务
     */
    @Override
    public IntegralTaskVo queryById(Long ID){
        return baseMapper.selectVoById(ID);
    }

    /**
     * 查询积分任务列表
     */
    @Override
    public TableDataInfo<IntegralTaskVo> queryPageList(IntegralTaskBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<IntegralTask> lqw = buildQueryWrapper(bo);
        Page<IntegralTaskVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        List<IntegralTaskVo> records = result.getRecords();
        //去查询该用户是否完成对应任务
        for (IntegralTaskVo record : records) {

            LambdaQueryWrapper<PointsDetails> lqw1 = Wrappers.lambdaQuery(PointsDetails.class)
                    .eq(PointsDetails::getUserId, SecurityUtils.getUserId())
                    .eq(PointsDetails::getTaskId, record.getID().toString())
                    .eq(record.getRewardType().equals("2"),PointsDetails::getChangeTime,new Date())
                    .eq(PointsDetails::getDelFlag,"0");
            List<PointsDetails> pointsDetails = pointsDetailsMapper.selectList(lqw1);

            //单次奖励
            if (record.getRewardType().equals("1")){
                if (pointsDetails.size() > 0){
                    record.setIsFinish("1");
                }else {
                    record.setIsFinish("0");
                }
            }else if (record.getRewardType().equals("2")){//循环奖励
                if (record.getNumberOfCycles()<=pointsDetails.size()){
                    record.setIsFinish("1");
                }else {
                    record.setIsFinish("0");
                }
            }
        }

        return TableDataInfo.build(result);
    }

    /**
     * 查询积分任务列表
     */
    @Override
    public List<IntegralTaskVo> queryList(IntegralTaskBo bo) {
        LambdaQueryWrapper<IntegralTask> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<IntegralTask> buildQueryWrapper(IntegralTaskBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<IntegralTask> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getTask()), IntegralTask::getTask, bo.getTask());
        lqw.eq(bo.getRewardsPoints() != null, IntegralTask::getRewardsPoints, bo.getRewardsPoints());
        lqw.eq(bo.getTotalPointsAwarded() != null, IntegralTask::getTotalPointsAwarded, bo.getTotalPointsAwarded());
        lqw.eq(bo.getPeriodOfValidity() != null, IntegralTask::getPeriodOfValidity, bo.getPeriodOfValidity());
        lqw.eq(bo.getRuleUpdateTime() != null, IntegralTask::getRuleUpdateTime, bo.getRuleUpdateTime());
        lqw.eq(StringUtils.isNotBlank(bo.getState()), IntegralTask::getState, bo.getState());
        lqw.eq(StringUtils.isNotBlank(bo.getBriefing()), IntegralTask::getBriefing, bo.getBriefing());
        lqw.eq(bo.getEndDate() != null, IntegralTask::getEndDate, bo.getEndDate());
        lqw.eq(StringUtils.isNotBlank(bo.getTaskValidityPeriod()), IntegralTask::getTaskValidityPeriod, bo.getTaskValidityPeriod());
        lqw.eq(StringUtils.isNotBlank(bo.getConditions()), IntegralTask::getConditions, bo.getConditions());
        lqw.eq(StringUtils.isNotBlank(bo.getParticipationLevel()), IntegralTask::getParticipationLevel, bo.getParticipationLevel());
        lqw.eq(bo.getConsumption() != null, IntegralTask::getConsumption, bo.getConsumption());
        lqw.eq(StringUtils.isNotBlank(bo.getRewardType()), IntegralTask::getRewardType, bo.getRewardType());
        lqw.eq(StringUtils.isNotBlank(bo.getCircularRule()), IntegralTask::getCircularRule, bo.getCircularRule());
        lqw.eq(bo.getCycleTime() != null, IntegralTask::getCycleTime, bo.getCycleTime());
        lqw.eq(bo.getNumberOfCycles() != null, IntegralTask::getNumberOfCycles, bo.getNumberOfCycles());
        lqw.eq(bo.getCyclicIntegral() != null, IntegralTask::getCyclicIntegral, bo.getCyclicIntegral());
        lqw.eq(StringUtils.isNotBlank(bo.getIsShow()), IntegralTask::getIsShow, bo.getIsShow());
        lqw.eq(StringUtils.isNotBlank(bo.getIntegralTypeCode()), IntegralTask::getIntegralTypeCode, bo.getIntegralTypeCode());
        lqw.eq(StringUtils.isNotBlank(bo.getIntegralTypeLable()), IntegralTask::getIntegralTypeLable, bo.getIntegralTypeLable());
        lqw.eq(IntegralTask::getDelFlag,"0");
        return lqw;
    }

    /**
     * 新增积分任务
     */
    @Override
    public Boolean insertByBo(IntegralTaskBo bo) {
        IntegralTask add = BeanUtil.toBean(bo, IntegralTask.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setID(add.getID());
        }
        return flag;
    }

    /**
     * 修改积分任务
     */
    @Override
    public Boolean updateByBo(IntegralTaskBo bo) {
        IntegralTask update = BeanUtil.toBean(bo, IntegralTask.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(IntegralTask entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除积分任务
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    /**
     * 积分任务
     * @param taskId
     * @param userId
     * @return
     */
    @Async
    @Override
    public IntegralTask pointsRule(String taskId, String userId) {
//        IntegralTask integralTask = baseMapper.selectTask(taskId);
        IntegralTask integralTask = baseMapper.selectById(taskId);
        int countTodayNum = pointsDetailsMapper.countTodayNum(userId,integralTask.getTask());
        VipUserInfo vipUserInfo = vipUserInfoMapper.selectUserUsableIntegral(userId);
        Long newRecordId=null;
        if (countTodayNum<integralTask.getNumberOfCycles()){
            long resultUsableIntegral = vipUserInfo.getUsableIntegral() + integralTask.getCyclicIntegral();
            long resultSumIntegral = vipUserInfo.getSumIntegral() + integralTask.getCyclicIntegral();

            PointsDetails pd=new PointsDetails();
            pd.setChangeType("5");
            pd.setUserId(userId);
            pd.setVariablePoints(integralTask.getCyclicIntegral());
            pd.setTaskId(Long.valueOf(taskId));
            pd.setBeforePoints(vipUserInfo.getUsableIntegral());
            pd.setCreateBy(userId);
            pd.setChangeTime(new Date());
            pd.setTask(integralTask.getTask());
            pd.setCreateTime(new Date());
            pointsDetailsMapper.insert(pd);
            newRecordId = pd.getID();

            UpdateWrapper<VipUserInfo> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("id", userId)
                    .set("usable_integral", resultUsableIntegral)
                    .set("sum_integral", resultSumIntegral);
            vipUserInfoMapper.update(null, updateWrapper);

            QueryWrapper<VipUserInfo> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("id", userId);
            VipUserInfo selectOne = vipUserInfoMapper.selectOne(queryWrapper);

            UpdateWrapper<PointsDetails> updatePdWrapper = new UpdateWrapper<>();
            updatePdWrapper.eq("ID",newRecordId)
                    .set("after_points",selectOne.getUsableIntegral());
            pointsDetailsMapper.update(null,updatePdWrapper);
        }

        return integralTask;
    }
}
